package com.demo.controller;

import com.demo.common.Result;
import com.demo.pojo.entity.Request;
import com.demo.service.RequestService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 诉求控制器（学生/教师使用）
 */
@RestController
@RequestMapping("/request")
@CrossOrigin
public class RequestController {
    
    @Autowired
    private RequestService requestService;
    
    /**
     * 提交诉求
     */
    @PostMapping("/submit")
    public Result<Boolean> submitRequest(@RequestBody Request request) {
        try {
            System.out.println("📝 收到诉求提交请求: " + request.getTitle());
            boolean result = requestService.submitRequest(request);
            return result ? Result.success(true).setMessage("诉求提交成功") : Result.error("诉求提交失败");
        } catch (Exception e) {
            System.err.println("❌ 提交诉求异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("提交诉求失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取用户的诉求列表
     */
    @GetMapping("/my-requests")
    public Result<List<Request>> getMyRequests(
            @RequestParam Long userId,
            @RequestParam String userType,
            @RequestParam(required = false) String status) {
        try {
            System.out.println("🔍 查询我的诉求: userId=" + userId + ", userType=" + userType);
            List<Request> list = requestService.getUserRequests(userId, userType, status);
            return Result.success(list);
        } catch (Exception e) {
            System.err.println("❌ 查询我的诉求异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("查询失败: " + e.getMessage());
        }
    }
    
    /**
     * 删除诉求（仅未处理的可以删除）
     */
    @DeleteMapping("/{requestId}")
    public Result<Boolean> deleteRequest(@PathVariable Long requestId) {
        try {
            System.out.println("🗑️ 删除诉求: " + requestId);
            
            // 检查是否可以删除
            Request request = requestService.getById(requestId);
            if (request == null) {
                return Result.error("诉求不存在");
            }
            if (!"PENDING".equals(request.getStatus())) {
                return Result.error("只能删除待处理的诉求");
            }
            
            boolean result = requestService.deleteRequest(requestId);
            return result ? Result.success(true).setMessage("删除成功") : Result.error("删除失败");
        } catch (Exception e) {
            System.err.println("❌ 删除诉求异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("删除失败: " + e.getMessage());
        }
    }
}

